﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Qianli.DirSir.Common;
using Qianli.DirSir.Model;
using System.Data;

namespace Qianli.DirSir.DAL
{
    public class UserDAL
    {
        SQLHelper sqlhelper = new SQLHelper();
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="u">前台传过来的用户集合</param>
        /// <returns></returns>
        public int Login(Userinfo u)
        {
            string sql = "select * from Userinfo where UserName='" + u.UserName + "'";
            DataTable dt = sqlhelper.ExecDataTable(sql);
            if (dt.Rows.Count > 0)
            {
                if (dt.Rows[0][4].ToString() == u.UserPass)
                {
                    return 1;//代表登录成功
                }
                else
                {
                    return 0;//代表密码错误
                }
            }
            else
            {
                return 2;//代表用户名不存在
            }
        }
        /// <summary>
        /// 根据用户名和密码获取用户编号
        /// </summary>
        /// <param name="u"></param>
        /// <returns></returns>
        public int GetUserID(Userinfo u)
        {
            string sql = "select UserID from Userinfo where UserName='" + u.UserName + "' and UserPass='" + u.UserPass + "'";
            return Convert.ToInt32(sqlhelper.ExecScalar(sql));
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="u"></param>
        /// <returns></returns>
        public int Register(Userinfo u)
        {
            
            string sql = "select * from Userinfo where UserName='" + u.UserName + "'";
            DataTable dt = sqlhelper.ExecDataTable(sql);
            if(dt.Rows.Count>0)
            {
                if(dt.Rows[0][4].ToString()==u.UserName)
                {
                    return 0;
                }
                else
                {
                    u.RoleID = 1;
                    u.UserState = 1;
                    string resql = "insert into Userinfo(RoleID,ParenCompanyName,UserName,UserPass,UserState) values(" + u.RoleID + ",'" + u.ParenCompanyName + "','" + u.UserName + "','" + u.UserPass + "'," + u.UserState + ")";
                    return sqlhelper.ExecNonquery(resql);
                }
            }
            else
            {
                u.RoleID = 1;
                u.UserState = 1;
                string resql = "insert into Userinfo(RoleID,ParenCompanyName,UserName,UserPass,UserState) values(" + u.RoleID + ",'" + u.ParenCompanyName + "','" + u.UserName + "','" + u.UserPass + "'," + u.UserState + ")";
                return sqlhelper.ExecNonquery(resql);
            }
            
        }
    }
}
